package com.lai.note.interceptor;

import android.content.Context;
import android.content.SharedPreferences;

import java.io.IOException;
import java.util.HashSet;

import okhttp3.Interceptor;
import okhttp3.Response;

public class ReceivedCookiesInterceptor implements Interceptor {

    private Context context;

    public ReceivedCookiesInterceptor(Context context){
        super();
        System.out.println("进来了-->  ReceivedCookiesInterceptor");
        this.context = context;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());

        if (!originalResponse.headers("Set-Cookie").isEmpty()) {
            HashSet<String> cookies = new HashSet<>();

            for (String header : originalResponse.headers("Set-Cookie")) {
                if(header.contains("JSESSIONID")){
                    String jsessionid = header.substring(header.indexOf("JSESSIONID"), header.indexOf(";"));
                    System.out.println("||||||||||\n\n-----____-----JSESSIONID:--> "+jsessionid+"------________-------\n||||||||||\n\n");
                    cookies.add(jsessionid);
                }
            }

            SharedPreferences.Editor config = context.getSharedPreferences("config", context.MODE_PRIVATE)
                    .edit();
            config.putStringSet("cookie", cookies);
            System.out.println("cookies:-->"+cookies);
            config.commit();
        }

        return originalResponse;
    }
}